using System;
using System.Collections.Generic;
using System.Text;

namespace XiVo
{
  public class ScheduleItem : IComparable
  {
    public bool Enabled;
    public DateTime StartTime;
    public int Duration;
    public RepeatTypeEnum RepeatType;
    public bool[] DaysOfWeek;
    private string _name;
    public int Channel;
    TimeSpan preRecord = new TimeSpan(0, -2, 0);
    TimeSpan postRecord = new TimeSpan(0, 0, 0);


    public ScheduleItem()
    {
      Enabled = true;
      Name = "New Event";
      StartTime = DateTime.Now;
      Duration = 30;
      RepeatType = RepeatTypeEnum.Once;
      DaysOfWeek = new bool[7];
      DaysOfWeek[(int)StartTime.DayOfWeek] = true;
      Channel = 1;
    }

    public ScheduleItem(int channel)
      : this()
    {
      this.Channel = channel;
    }

    public enum RepeatTypeEnum
    {
      Once = 0,
      Weekly = 1,
      Daily = 2
    }

    public string Name
    {
      get { return _name; }
      set { _name = value; }
    }

    public DateTime RecordStartTime()
    {
      if (StartTime == DateTime.MinValue)
        return StartTime;
      else
        return StartTime + preRecord;
    }

    public DateTime EndTime
    {
      get { return StartTime.AddMinutes(Duration) + postRecord; }
    }

    public bool isCurrent()
    {
      if (Enabled
        && StartTime != DateTime.MinValue
        && RecordStartTime() <= DateTime.Now
        && EndTime > DateTime.Now)
        return true;
      else
        return false;
    }

    public bool isActive()
    {
      return EndTime >= DateTime.Now && Enabled;
    }

    public void setNextRepeat()
    {
      if (isCurrent() == false)
      {
        switch (RepeatType)
        {
          case RepeatTypeEnum.Daily:
            while (StartTime <= DateTime.Now)
              StartTime = StartTime.AddDays(1);
            break;
          case RepeatTypeEnum.Weekly:
            bool repeatOk = false;
            foreach (bool b in DaysOfWeek)
            {
              if (b)
              {
                repeatOk = true;
                break;
              }
            }
            if (repeatOk)
              while (StartTime <= DateTime.Now || DaysOfWeek[(int)StartTime.DayOfWeek] == false)
                StartTime = StartTime.AddDays(1);
            break;
        }
      }
    }



    #region IComparable Members

    public int CompareTo(object obj)
    {
      if (obj.GetType() != this.GetType())
        throw new Exception("Cannot compare disparate types");

      ScheduleItem comp = (ScheduleItem)obj;
      return this.StartTime.CompareTo(comp.StartTime);
    }

    #endregion
  }
}
